package gui.finalsOptions;


import java.sql.SQLException;
import java.util.HashSet;
import java.util.Iterator;

import table.models.FinalsOptionsTableModel;
import tournamentData.TournamentData;
import core.GuiComponentLabels;
import core.Person;
import dataBase.DbHolder;
import db.newversion.Combination;

public class FinalsOptionsController {
	FinalsOptionsWindow window;

	public FinalsOptionsController(FinalsOptionsWindow finalsOptionsWindow) {
		this.window = finalsOptionsWindow;
	}

	public void savePermissions() {
		for (int i = 0; i < this.window.getFinalsPermissionsTable().getRowCount(); i++) {
			String bowCathegory = this.window.getFinalsPermissionsTable().getValueAt(i, 0).toString();
			String ageClass = this.window.getFinalsPermissionsTable().getValueAt(i, 1).toString();
			String gender = this.window.getFinalsPermissionsTable().getValueAt(i, 2).toString();
			boolean hasPermission = new Boolean(this.window.getFinalsPermissionsTable().getValueAt(i, 3).toString());

			try {
				DbHolder.getInstance().getArcherData().insertPermission(bowCathegory, ageClass, gender, hasPermission);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	public void closeWindow() {
		this.window.dispose();
	}

	public void buildTable() {
		FinalsOptionsTableModel model = new FinalsOptionsTableModel(new String [] { GuiComponentLabels.BOW_CATHEGORY, GuiComponentLabels.AGE_CLASS, GuiComponentLabels.GENDER,
				GuiComponentLabels.FINALS_PERMISSION });

		HashSet < Combination > combinations = new HashSet < Combination >();
		for (int i = 0; i < TournamentData.getInstance().getAllParticipants().length; i++) {
			Person person = DbHolder.getInstance().getArcherData().getById(TournamentData.getInstance().getAllParticipants() [i]);
			combinations.add(new Combination(person.getBowCathegory(), person.getAgeClass(), person.getGender()));
		}
		Iterator < Combination > iterator = combinations.iterator();
		while (iterator.hasNext()) {
			Combination current = iterator.next();
			model.addRow(new Object [] { current.getBowCathegory(), current.getAgeClass(), current.getGender(),
					DbHolder.getInstance().getArcherData().hasPermission(current.getBowCathegory(), current.getAgeClass(), current.getGender()) });

		}

		this.window.getFinalsPermissionsTable().setModel(model);
	}
}
